// pages/order/order.js
const appdata = getApp()
const AV = getApp().globalData.AV
Page({

    /**
     * 页面的初始数据
     */
    data: {
        index: 0, //头部的index改变样式改变
        date: '选择配送日期', //配送日期
        array: ['09:30-11:30', '11:30-13:30', '13:30-15:30', '15:30-18:30', '18:30-21:30'], //时间段
        hourIndex: 0, //时间段的下标
        openid: '',
        updatedAt: '',
        bindDate: true,
        bindPicker: true,
        windowbind: true,
        Times: '',
        num: '',
        countdown: '', // 5分钟倒计时
        addressList: [], //地址列表
        address: [], //单个地址列表
        addressid: '', //地址id
        switch: false, //遮罩层的开关
        scrollStyle: '', //禁止滑动
        id: [], //购物车列表的objectId
        list: [], //列表
        totalPrice: 0, //总价
    },

    // 打开地址弹窗
    window() {
        this.setData({
            switch: !this.data.switch,
            scrollStyle: 'disableScroll' //禁止滚动
        })
    },
    // 关闭地址弹窗
    closeSize() {
        this.setData({
            switch: false,
            scrollStyle: ''
        })
    },
    // 修改地址
    gotochangeaddress(e) {
        wx.navigateTo({
            url: '/pages/newAddress/newAddress?objectid=' + e.currentTarget.dataset.index,
        })
    },
    // 新建地址
    newAddress() {
        wx.navigateTo({
            url: '/pages/newAddress/newAddress?nameIndex=' + '1',
        })
    },
    // 改变配送日期
    bindDateChange: function (e) {
        this.setData({
            date: e.detail.value
        })
        for (let i = 0; i < this.data.id.length; i++) {
            const todo = AV.Object.createWithoutData("cart", this.data.id[i]);
            todo.set('date', this.data.date)
            todo.save()
        }

    },
    // 改变具体时间段
    bindPickerChange(e) {
        this.setData({
            hourIndex: e.detail.value
        })
        for (let i = 0; i < this.data.id.length; i++) {
            const todo = AV.Object.createWithoutData("cart", this.data.id[i]);
            todo.set('hour', this.data.array[this.data.hourIndex])
            todo.save()
        }

    },
    // 地址详情
    updateaAddress() {
        const query = new AV.Query('address');
        
        if (this.data.addressid !== '') {
            query.equalTo('objectId', this.data.addressid);
        }
        query.equalTo('openId', this.data.openid);
        query.find().then((res) => {
            this.setData({
                address: res,
                switch: false
            })
            console.log(res); // 单个地址列表
            this.stater()
        })
    },
    // 切换地址事件
    bindAddress(e) {
        console.log(e);
        this.setData({
            addressid: e.detail.value
        })
        this.updateaAddress()
    },
    stater() { // 修改待支付 增加地址
        console.log(this.data.address[0].id);
        for (let index = 0; index < this.data.id.length; index++) {
            const query = new AV.Query('cart');
            query.equalTo('stater', '2');
            query.equalTo('addressId', this.data.address[0].id);
            query.find().then((students) => {
                console.log(students);
                console.log(9);
                const todo = AV.Object.createWithoutData('cart', this.data.id[index]);
                todo.set('stater', '2');
                todo.set('addressId', this.data.address[0].id);
                todo.save().then((todo) => {})

            })
        }
    },
    addressing() { //全部地址
        const query = new AV.Query('address');
      
        query.equalTo('openId', this.data.openid);
        query.find().then((students) => {
            console.log(students);
            this.setData({
                addressList: students
            })
        })
    },
    listadd() { // 列表 总数 总价
        let arr = []
        for (let index = 0; index < this.data.id.length; index++) {
            const query = new AV.Query('cart');
            // query.equalTo('stater', '0');
            query.equalTo('objectId', this.data.id[index]);
            query.find().then((students) => {
                arr.push(students[0])
                this.setData({
                    list: arr,
                    totalPrice: this.data.totalPrice += arr[index].attributes.price * arr[index].attributes.number
                })
            })
        }
    },
    // 支付
    payTotal() {
        if (this.data.totalPrice > 0) {
            wx.showToast({
                title: '支付成功',
            })
            for (let i = 0; i < this.data.id.length; i++) {
                const todo = AV.Object.createWithoutData("cart", this.data.id[i]);
                // 支付状态
                todo.set("stater", "3");
                todo.save().then(() => {
                    wx.switchTab({
                        url: '/pages/my/my',
                    })
                })
            }


        }
    },
    orderadd() { // 代付款跳转
        let arr = []
        for (let index = 0; index < this.data.id.length; index++) {
            const query = new AV.Query('cart');
            query.equalTo('stater', '2');
            query.equalTo('objectId', this.data.id[index]);
            query.find().then((students) => {
                arr.push(students[0])
                // console.log(arr);
                this.setData({
                    list: arr,
                    totalPrice: this.data.totalPrice += arr[index].attributes.price * arr[index].attributes.number,
                    date: arr[0].attributes.date,
                    hour: arr[0].attributes.hour
                })
                this.setData({
                    updatedAt: students[0].updatedAt,

                })
                this.addetsd(students[0].attributes.addressId)
                this.timestampToTime(this.data.updatedAt)
            })
        }
    },
    addetsd(id) { // 收货地址
        console.log(id);
        const query = new AV.Query('address');
        // query.equalTo('stater', '0');
        query.equalTo('objectId', id);
        query.find().then((students) => {
            console.log(students);
            this.setData({
                address: students
            })
        })
    },
    timestampToTime(updatedAt) { // 代付款时间格式化
        let chinaStandard = updatedAt;
        let date = new Date(chinaStandard);
        let y = date.getFullYear();
        let Time
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        let d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        let h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        let minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        let second = date.getSeconds();
        second = second < 10 ? ('0' + second) : second;
        Time = y + '/' + m + '/' + d + ' ' + h + ':' + minute + ':' + second;
        console.log(Time);
        this.setData({
            Times: Time
        })
        this.countDown()
    },
    countDown() { //代付款倒计时
        let that = this
        let starttime = that.data.Times
        let start = new Date(starttime.replace(/-/g, '/')).getTime();
        let endTime = start + 5 * 60000 // 十五分钟后的时间戳
        let date = new Date(); //现在时间
        let now = date.getTime(); //现在时间戳
        let allTime = endTime - now
        let m, s;
        if (allTime > 0) {
            m = Math.floor(allTime / 1000 / 60 % 60);
            s = Math.floor(allTime / 1000 % 60);

            function mdata(m) {
                if (m < 10) {
                    return "0" + m;
                } else {
                    return m;
                }
            }

            function sdata(s) {
                if (s < 10) {
                    return "0" + s;
                } else {
                    return s;
                }
            }
            that.setData({
                countdown: mdata(m) + "分" + sdata(s) + "秒",
            })
            setTimeout(that.countDown, 1000);
        } else {
            for (let index = 0; index < this.data.id.length; index++) {
                const todo = AV.Object.createWithoutData('cart', this.data.id[index]);
                todo.set('stater', '6');
                todo.save().then((todo) => {
                    wx.navigateBack({
                        delta: 1, // 返回上一级页面。
                        success: function () {
                            wx.showToast({
                                title: "订单关闭"
                            })
                        }
                    })
                })
            }
        }
    },

    orderaddind() { // 代发货
        let arr = []
        for (let index = 0; index < this.data.id.length; index++) {
            const query = new AV.Query('cart');
            query.equalTo('stater', '3');
            query.equalTo('objectId', this.data.id[index]);
            query.find().then((students) => {
                arr.push(students[0])
                this.setData({
                    list: arr,
                    totalPrice: this.data.totalPrice += arr[index].attributes.price * arr[index].attributes.number,
                    date: arr[0].attributes.date,
                    hour: arr[0].attributes.hour
                })
                this.setData({
                    updatedAt: students[0].updatedAt,
                })
                this.addetsd(students[0].attributes.addressId)
                this.timestampToTimes(this.data.updatedAt)
            })
        }
    },
    timestampToTimes(updatedAt) { // 代发货时间格式化
        let chinaStandard = updatedAt;
        let date = new Date(chinaStandard);
        let y = date.getFullYear();
        let Time
        let m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        let d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        let h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        let minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        let second = date.getSeconds();
        second = second < 10 ? ('0' + second) : second;
        Time = y + '/' + m + '/' + d + ' ' + h + ':' + minute + ':' + second;
        this.setData({
            Times: Time
        })
        this.countDownsing()
    },
    countDownsing() { //代发货倒计时
        let that = this
        let starttime = that.data.Times
        let start = new Date(starttime.replace(/-/g, '/')).getTime();
        let endTime = start + 5 * 60000 // 五分钟后的时间戳
        let date = new Date(); //现在时间
        let now = date.getTime(); //现在时间戳
        let allTime = endTime - now
        var m, s;
        if (allTime > 0) {
            m = Math.floor(allTime / 1000 / 60 % 60);
            s = Math.floor(allTime / 1000 % 60);

            function mdata(m) {
                if (m < 10) {
                    return "0" + m;
                } else {
                    return m;
                }
            }

            function sdata(s) {
                if (s < 10) {
                    return "0" + s;
                } else {
                    return s;
                }
            }
            that.setData({
                countdown: mdata(m) + "分" + sdata(s) + "秒",
            })
            setTimeout(that.countDownsing, 1000);
        } else {
            for (let index = 0; index < this.data.id.length; index++) {
                const todo = AV.Object.createWithoutData('cart', this.data.id[index]);
                todo.set('stater', '4');
                todo.save().then((todo) => {
                    wx.navigateBack({
                        delta: 1, // 返回上一级页面。
                        success: function () {
                            wx.showToast({
                                title: "已发货，请等待收货"
                            })
                        }
                    })
                })
            }
        }
    },
    orderaddindse() { // 代收货
        let arr = []
        for (let index = 0; index < this.data.id.length; index++) {
            const query = new AV.Query('cart');
            query.equalTo('stater', '4');
            query.equalTo('objectId', this.data.id[index]);
            query.find().then((students) => {
                console.log(students);
                arr.push(students[0])
                this.setData({
                    list: arr,
                    totalPrice: this.data.totalPrice += arr[index].attributes.price * arr[index].attributes.number,
                    date: arr[0].attributes.date,
                    hour: arr[0].attributes.hour
                })
                this.setData({
                    updatedAt: students[0].updatedAt,
                })
                this.addetsd(students[0].attributes.addressId)
                this.timestampToTimesmag(this.data.updatedAt)
            })
        }
    },
    timestampToTimesmag(updatedAt) { // 代收货时间格式化
        var chinaStandard = updatedAt;
        var date = new Date(chinaStandard);
        var y = date.getFullYear();
        let Time
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        var second = date.getSeconds();
        second = second < 10 ? ('0' + second) : second;
        Time = y + '/' + m + '/' + d + ' ' + h + ':' + minute + ':' + second;
        this.setData({
            Times: Time
        })
        this.countDownsmag()
    },
    countDownsmag() { //代收货倒计时
        var that = this
        var starttime = that.data.Times
        var start = new Date(starttime.replace(/-/g, '/')).getTime();
        var endTime = start + 5 * 60000 // 十五分钟后的时间戳
        var date = new Date(); //现在时间
        var now = date.getTime(); //现在时间戳
        var allTime = endTime - now
        var m, s;
        if (allTime > 0) {
            m = Math.floor(allTime / 1000 / 60 % 60);
            s = Math.floor(allTime / 1000 % 60);

            function mdata(m) {
                if (m < 10) {
                    return "0" + m;
                } else {
                    return m;
                }
            }

            function sdata(s) {
                if (s < 10) {
                    return "0" + s;
                } else {
                    return s;
                }
            }
            that.setData({
                countdown: mdata(m) + "分" + sdata(s) + "秒",
            })
            setTimeout(that.countDownsmag, 1000);
        } else {
            for (let index = 0; index < this.data.id.length; index++) {
                const todo = AV.Object.createWithoutData('cart', this.data.id[index]);
                todo.set('stater', '5');
                todo.save().then((todo) => {
                    wx.navigateBack({
                        delta: 1, // 返回上一级页面。
                        success: function () {
                            wx.showToast({
                                title: "已确认收货"
                            })
                        }
                    })
                })
            }
        }
    },
    // 再来一单
    payTotals() {
    //    console.log(this.data.list);
        wx.navigateTo({
            url: '/pages/detail/detail?title=' + this.data.list[0].attributes.listName + '&id=' + this.data.list[0].attributes.id
        })
    },
    // 支付完成事件
    payTotalss() {
        for (let index = 0; index < this.data.id.length; index++) {
            const todo = AV.Object.createWithoutData('cart', this.data.id[index]);
            todo.set('stater', '5');
            todo.save().then((todo) => {
                // this.orderaddindse()
                wx.navigateBack({
                    delta: 1, // 返回上一级页面。
                    success: function () {
                        wx.showToast({
                            title: "确认收货成功"
                        })
                    }
                })
            })
        }
    },
    onLoad: function (options) {
        const id = options.id.split(',')
        const newArr = []
        for (var i = 0; i < id.length; i++) {
            if (newArr.indexOf(id[i]) == -1) {
                newArr.push(id[i])
            }
        }
        this.setData({
            id: newArr,
            num: options.num
        })
        if (options.num === '2') {
            // 待付款
            this.orderadd()
            this.setData({
                bindDate: false,
                bindPicker: false,
                windowbind: false,
            })
        } else if (options.num === '3') {
            // 代发货
            this.orderaddind()
            this.setData({
                bindDate: false,
                bindPicker: false,
                windowbind: false,
            })
        } else if (options.num === '4') {
            // 代收货
            this.orderaddindse()
            this.setData({
                bindDate: false,
                bindPicker: false,
                windowbind: false,
            })
        } else {
            this.listadd()
        }
        
    },
    onShow: function () {
        const openid = appdata.globalData.userInfo
        this.setData({
            openid: openid
        })
        if (this.data.num === '0') {
            this.updateaAddress()
            this.addressing()
            this.setData({
                bindDate: true,
                bindPicker: true,
                windowbind: true,
            })
        }
        // if (this.data.num === '2') {
        //     // this.updateaAddress()
        //     // this.addressing()
        //     // this.setData({
        //     //     bindDate: true,
        //     //     bindPicker: true,
        //     //     windowbind: true,
        //     // })
        // }
        // if (this.data.num === '3') {

        // }
        // if (this.data.num === '4') {

        // }
    },




})